﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GrainManage.Data.Util;
using GrainManage.Data.Model.Table;
using GrainManage.Data.Model;

namespace GrainManage.Data.Service
{
    public class BaseService
    {
        protected GrainManage.Data.Access.AccessBase Proc { get; private set; }
        protected GrainManage.Data.Pattern.IPattern Pattern { get; private set; }

        public BaseService(GrainManage.Data.Access.AccessBase proc)
        {
            this.Proc = proc;
        }

        public BaseService(GrainManage.Data.Access.AccessBase proc, GrainManage.Data.Pattern.IPattern pattern)
        {
            this.Proc = proc;
            this.Pattern = pattern;
        }

        protected static int GetTotalRowCount(DataSet table)
        {
            int totalRow = 0;
            if (table != null && table.Tables != null && table.Tables.Count == 2)
            {
                totalRow = Convert.ToInt32(table.Tables[1].Rows[0][0]);
            }
            return totalRow;
        }

        protected static int GetOffset(IPageable page)
        {
            return page.PageIndex * page.PageSize;
        }

        protected static DataRow GetFirstRow(DataSet ds)
        {
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0];
            }
            return null;
        }

        protected static List<TModel> ConvertToModel<TModel>(DataSet table, ICountable records) where TModel : class,new()
        {
            List<TModel> result = new List<TModel>();
            if (table != null && table.Tables.Count > 0)
            {
                result = Convertor.ConvertToEntity<TModel>(table.Tables[0]);
            }
            records.Total = GetTotalRowCount(table);
            return result;
        }

        protected static TModel ConvertToModel<TModel>(DataRow row) where TModel : class,new()
        {
            TModel result = default(TModel);
            if (row != null)
            {
                result = Convertor.ConvertToEntity<TModel>(row);
            }
            return result;
        }
    }
}
